﻿
using PSE.Framework.Communication.Configuration.Adapters.File.ExcelFile;
using PSE.Framework.Communication.Adapters.File;
using PSE.Framework.Communication.Configuration.Adapters;
using PSE.Framework.Communication.Configuration.File;
using PSE.Framework.Communication.Configuration.File.ExcelFile;
using FileHelpers.DataLink;
using System;
using PSE.Framework.Communication.Configuration.Exceptions;

namespace PSE.Framework.Communication.Adapters.File.ExcelFile
{
    public class ExcelFileOutputAdapter : FileOutputAdapter<ExcelFileOutputConfiguration>
    {
        #region Atributos

        private ExcelStorage _storage = null;
        private bool _fixedType = false;

        #endregion

        #region Construtor

        public ExcelFileOutputAdapter()
        {

        }

        #endregion

        #region Métodos

        protected override void Send(object message)
        {
            //Escreve os dados no arquivo
            _storage.InsertNextRecord(message);
        }

        protected override object Serialize(object message, string action)
        {
            return message;
        }

        protected override void CreateAndOpenFile(string fullPath)
        {
            //while (!System.Diagnostics.Debugger.IsAttached)
            //    System.Threading.Thread.Sleep(1000);            

            Type recordType;

            // Capturando type
            if (this.Configuration.Actions[0].SerializedMessageType != null)
            {
                recordType = this.Configuration.Actions[0].SerializedMessageType;
                _fixedType = true;
            }
            else if (!string.IsNullOrEmpty(this.Configuration.Actions[0].SerializedMessageFile))
            {
                recordType = FileHelpers.RunTime.ClassBuilder.ClassFromXmlFile(this.Configuration.Actions[0].SerializedMessageFile);
                _fixedType = false;
            }
            else
            {
                throw new InvalidAdapterConfigurationException("Type and SerializedMessageFile were not informed", this.Configuration.Name);
            }

            _storage = new ExcelStorage(recordType, fullPath, 1, 1);
            _storage.SheetName = this.Configuration.SheetName;

            _storage.BeginInsertRecords();

            if (_storage.ColumnList != null && _storage.ColumnList.Count > 0)
                _storage.InsertHeaderRow(_storage.ColumnList.ToArray());
        }

        protected override void CloseFile()
        {
            if (_storage != null)
            {
                _storage.EndInsertRecords();
                _storage = null;
            }
            _fixedType = false;
        }

        #endregion

    }//end ExcelFileOutputAdapter

}
